(function () {

    var ns = {
        ajax : bump.$core.namespace('bump.framework.ajax')
    };

    ns.ajax.AjaxRenderer = function() {

        this.inProgress = false;
        this.beforeRender = null;
        this.afterRender = null;

        this.render = function(o) {
            if ( this.inProgress ) return;

            this.inProgress = true;

            var
            shim = new ns.ajax.AjaxShim(),
            container = $('#' + o.containerId),
            template = container.find('.ajax-template:first').text(),
            serverRenderer = Seam.Component.getInstance('ajaxRenderer'),
            map = null;

            shim.bindToContainer(container);

            if ( o.data ) {
                map = new Seam.Remoting.Map();
                for (var key in o.data) map.put(key, o.data[key]);
            }

            var self = this;

            if ( o.beforeRender ) o.beforeRender();

            serverRenderer.renderBody(template, map, function(result) {
                self.inProgress = false;
                shim.remove();

                var content = container.find('.ajax-content'), resultHtml = $(result);

                if ( o.renderType == 'append' ) {
                    content.append(resultHtml);
                } else if ( o.renderType == 'replace' ) {
                    content.html(resultHtml);
                } else if ( o.renderType == 'custom' ) {
                    o.renderCallback(content, resultHtml);
                }

                if ( o.afterRender ) o.afterRender();
            });
        };

        this.bindToLink = function(o) {
            var self = this;

            o.link.click(function() {
                self.render(o);
                return false;
            });
        };

    };

    $(document).ready(function() {
        ns.ajax.ajaxUi.hideSeamAjaxLoader();
    });

})();
